<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import { logout } from '@/api/auth'; // 导入新的 logout 函数

export default {
  name: 'App',
  mounted() {
    window.addEventListener('unload', this.handleUnload);
  },
  beforeDestroy() {
    window.removeEventListener('unload', this.handleUnload);
  },
  methods: {
    handleUnload() {
      // 尝试从 localStorage 获取 token 和 device_id
      const accessToken = localStorage.getItem('access_token');
      const deviceId = localStorage.getItem('device_id');

      // 检查用户是否已登录
      if (accessToken && deviceId) {
        // 调用封装的 logout 函数，并传入 true 以使用 keepalive
        logout(deviceId, accessToken, true)
          .then(success => {
            // 在 unload 中通常不处理响应，但可以保留日志以供调试
            if (success) {
              // console.log('Logout request dispatched via keepalive.');
            } else {
              // console.error('Failed to dispatch logout request via keepalive.');
            }
          });
      }

      // 清理本地存储
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('user_info');
      localStorage.removeItem('device_id');
    }
  }
}
</script>

<style>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

#app {
  height: 100%;
}
</style>